import os
import csv

def scan_md_files(root_dir):
    """
    扫描目录中的.md文件，排除_cr.md文件，并过滤内容不包含"## Dao层接口"的文件
    """
    matched_files = []
    for foldername, _, filenames in os.walk(root_dir):
        for filename in filenames:
            # 筛选.md文件并排除_cr.md文件
            if filename.endswith('.md') and not filename.endswith('_cr.md'):
                file_path = os.path.join(foldername, filename)
                # 检查文件内容是否不包含目标字符串
                if not contains_target_string(file_path):
                    matched_files.append(os.path.abspath(file_path))
    return matched_files

def contains_target_string(file_path):
    """
    检查文件内容是否包含目标字符串"## Dao层接口"
    """
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            return any("## Dao层接口" in line for line in f)
    except Exception as e:
        print(f"错误：无法读取文件 {file_path} - {str(e)}")
        return True  # 出错时视为包含目标字符串，跳过该文件

def write_to_csv(file_paths, output_file="output.csv"):
    """
    将文件路径列表写入CSV文件
    """
    with open(output_file, 'w', newline='', encoding='utf-8') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow(["File Path"])  # 写入标题
        for path in file_paths:
            writer.writerow([path])

if __name__ == "__main__":
    # 配置路径（根据实际需求修改）
    target_dir = r"C:\\Users\\zhang\\mall\\mall-mbg\\src\\main\\java\\com\\macro\\mall\\mapper"
    output_file = "output.csv"
    
    # 执行扫描和写入操作
    matched_files = scan_md_files(target_dir)
    write_to_csv(matched_files, output_file)
    
    print(f"扫描完成！共找到 {len(matched_files)} 个符合条件的文件")
    print(f"结果已保存至: {os.path.abspath(output_file)}")